import {
  ApiOutlined,
  BugOutlined,
  CodeOutlined,
  DashboardOutlined,
  ExperimentOutlined,
  RocketOutlined,
  SafetyOutlined,
  ToolOutlined,
} from "@ant-design/icons"
import { Slide } from "../types"

// 重新排序的slides，按照核心使用场景顺序
export const slides: Slide[] = [
  {
    id: "welcome",
    title: "首页", // 导航栏显示
    subtitle: "Claude 前端开发实战指南", // 页面内容显示
    type: "title",
    description: "通过实际案例，展示如何使用Claude提升前端开发效率",
    tags: ["React", "TypeScript", "Ant Design", "GitLab CI", "Best Practices"],
  },
  {
    id: "overview",
    title: "核心应用场景",
    type: "overview",
    items: [
      {
        icon: <CodeOutlined style={{ fontSize: "2rem", color: "#8B5CF6" }} />,
        title: "设计稿转代码",
        description: "上传设计稿截图，自动生成React组件代码，包含样式和交互",
      },
      {
        icon: (
          <DashboardOutlined style={{ fontSize: "2rem", color: "#EC4899" }} />
        ),
        title: "表单表格生成",
        description: "描述字段需求，快速生成完整的CRUD页面",
      },
      {
        icon: <ApiOutlined style={{ fontSize: "2rem", color: "#06B6D4" }} />,
        title: "接口联调",
        description: "API封装、Mock数据生成、接口调试、错误处理",
      },
      {
        icon: <SafetyOutlined style={{ fontSize: "2rem", color: "#10B981" }} />,
        title: "权限管理",
        description: "多层级权限控制、路由守卫、按钮级权限",
      },
      {
        icon: <BugOutlined style={{ fontSize: "2rem", color: "#F59E0B" }} />,
        title: "Bug修复",
        description: "系统化的问题定位、根因分析、修复方案生成",
      },
      {
        icon: <RocketOutlined style={{ fontSize: "2rem", color: "#EF4444" }} />,
        title: "复杂模块实现",
        description: "使用Plan Mode和思考模型，快速理解和实现复杂业务逻辑",
      },
      {
        icon: <ToolOutlined style={{ fontSize: "2rem", color: "#8B5CF6" }} />,
        title: "Git工作流",
        description: "自动化提交、分支管理、冲突解决、代码审查",
      },
      {
        icon: (
          <ExperimentOutlined style={{ fontSize: "2rem", color: "#EC4899" }} />
        ),
        title: "方案快速验证",
        description: "快速搭建原型、CI/CD配置、Docker部署等技术方案验证",
      },
    ],
  },
  {
    id: "design-to-code",
    title: "设计稿识别转代码",
    type: "code",
    description: "将UI设计稿直接转换为React组件代码",
    examples: [
      {
        title: "高质量提示词结构",
        description: "完整的提示词模板，确保生成高质量代码",
        prompt: `请将这个设计稿转换为React组件：

[上传设计稿截图]

## 技术要求
- 技术栈：React 18 + TypeScript + Ant Design 5
- 样式方案：Tailwind CSS + CSS Modules

## 布局描述
- 顶部：固定高度64px的导航栏
- 左侧：200px宽的侧边栏
- 主体：居中内容区，最大宽度1200px
- 底部：版权信息footer

## UI元素清单（从上到下）
1. 导航栏：Logo、搜索框、用户头像、通知图标
2. 侧边栏：多级菜单、收起按钮
3. 内容区：面包屑、标题、数据卡片、表格
4. 操作栏：筛选器、搜索、批量操作按钮

## 交互要求
- 点击菜单项高亮显示
- hover卡片显示阴影效果
- 表格支持排序和分页
- 搜索框支持实时搜索

## 数据处理
- 列表数据通过props传入
- 搜索和筛选在前端实现
- 分页请求调用API

## 代码质量
- 使用TypeScript严格类型
- 添加必要的注释
- 实现loading和error状态`,
        code: `import React from 'react';
import { Card, Button, Avatar, Space, Tag } from 'antd';
import { UserOutlined, HeartOutlined, MessageOutlined, ShareAltOutlined } from '@ant-design/icons';

interface UserCardProps {
  user: {
    name: string;
    role: string;
    avatar?: string;
    tags: string[];
    stats: {
      posts: number;
      followers: number;
      following: number;
    };
  };
}

const UserCard: React.FC<UserCardProps> = ({ user }) => {
  return (
    <Card className="w-full max-w-md shadow-lg hover:shadow-xl transition-shadow">
      <div className="text-center">
        <Avatar
          size={80}
          src={user.avatar}
          icon={<UserOutlined />}
          className="mb-4"
        />
        <h2 className="text-2xl font-bold text-gray-900 mb-1">{user.name}</h2>
        <p className="text-gray-600 mb-4">{user.role}</p>

        <Space wrap className="mb-4">
          {user.tags.map(tag => (
            <Tag key={tag} color="purple">{tag}</Tag>
          ))}
        </Space>

        <div className="grid grid-cols-3 gap-4 py-4 border-t border-b">
          <div>
            <div className="text-2xl font-bold text-gray-900">{user.stats.posts}</div>
            <div className="text-sm text-gray-500">Posts</div>
          </div>
          <div>
            <div className="text-2xl font-bold text-gray-900">{user.stats.followers}</div>
            <div className="text-sm text-gray-500">Followers</div>
          </div>
          <div>
            <div className="text-2xl font-bold text-gray-900">{user.stats.following}</div>
            <div className="text-sm text-gray-500">Following</div>
          </div>
        </div>

        <Space className="w-full mt-4" size="middle">
          <Button type="primary" block>Follow</Button>
          <Button block>Message</Button>
        </Space>
      </div>
    </Card>
  );
};

export default UserCard;`,
        language: "typescript",
      },
      {
        title: "迭代优化策略",
        description: "通过多轮对话逐步完善代码",
        prompt: `# 迭代优化流程

## 第一轮：生成基础结构
"根据设计稿生成页面基本结构和布局"

## 第二轮：调整样式细节
"请调整以下样式：
- 顶部padding改为24px
- 卡片圆角改为8px
- 主标题字号改为32px
- 按钮使用渐变背景"

## 第三轮：添加交互效果
"添加以下交互：
- 卡片hover时显示阴影并上移2px
- 按钮点击显示loading状态
- 输入框focus时边框变色
- 列表项添加进入动画"

## 第四轮：响应式优化
"适配移动端：
- 768px以下卡片改为垂直排列
- 侧边栏改为抽屉式
- 字号适当缩小
- 间距调整为移动端友好"

## 第五轮：性能优化
"优化性能：
- 大列表使用虚拟滚动
- 图片添加懒加载
- 组件添加memo优化
- 提取可复用组件"`,
        code: `// 第一轮：基础结构
<div className="container">
  <header>...</header>
  <main>...</main>
</div>

// 第二轮：样式细节
<div className="container pt-6">
  <Card className="rounded-lg">...</Card>
</div>

// 第三轮：交互效果
<Card
  className="rounded-lg hover:shadow-lg hover:-translate-y-0.5 transition-all"
  onMouseEnter={handleHover}
>
  <Button loading={loading} onClick={handleClick}>
    提交
  </Button>
</Card>

// 第四轮：响应式
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
  {items.map(item => (
    <Card key={item.id} className="w-full">
      {/* 内容 */}
    </Card>
  ))}
</div>

// 第五轮：性能优化
const MemoizedCard = React.memo(Card);
const VirtualList = React.lazy(() => import('./VirtualList'));`,
      },
      {
        title: "复杂布局示例",
        description: "包含网格、响应式、动画效果",
        code: `import React, { useState } from 'react';
import { Layout, Menu, Card, Row, Col, Statistic, Progress } from 'antd';
import {
  DashboardOutlined,
  UserOutlined,
  ShoppingCartOutlined,
  BarChartOutlined
} from '@ant-design/icons';

const { Header, Sider, Content } = Layout;

const Dashboard: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);

  const stats = [
    { title: '总用户', value: 1234, icon: 'UserOutlined', color: '#8B5CF6' },
    { title: '订单数', value: 567, icon: 'ShoppingCartOutlined', color: '#EC4899' },
    { title: '销售额', value: 89012, prefix: '¥', icon: 'BarChartOutlined', color: '#06B6D4' },
    { title: '完成率', value: 78, suffix: '%', icon: 'DashboardOutlined', color: '#10B981' }
  ];

  return (
    <Layout className="min-h-screen">
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo h-16 bg-purple-600 flex items-center justify-center">
          <h1 className="text-white text-xl font-bold">Logo</h1>
        </div>
        <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
          <Menu.Item key="1" icon={<DashboardOutlined />}>
            仪表盘
          </Menu.Item>
          <Menu.Item key="2" icon={<UserOutlined />}>
            用户管理
          </Menu.Item>
          <Menu.Item key="3" icon={<ShoppingCartOutlined />}>
            订单管理
          </Menu.Item>
        </Menu>
      </Sider>

      <Layout>
        <Header className="bg-white px-6 shadow-sm">
          <h2 className="text-xl font-semibold">数据概览</h2>
        </Header>

        <Content className="p-6 bg-gray-50">
          <Row gutter={[16, 16]}>
            {stats.map((stat, index) => (
              <Col xs={24} sm={12} lg={6} key={index}>
                <Card>
                  <Statistic
                    title={stat.title}
                    value={stat.value}
                    prefix={stat.prefix}
                    suffix={stat.suffix}
                    valueStyle={{ color: stat.color }}
                  />
                  <Progress
                    percent={stat.value > 100 ? 100 : stat.value}
                    showInfo={false}
                    strokeColor={stat.color}
                  />
                </Card>
              </Col>
            ))}
          </Row>
        </Content>
      </Layout>
    </Layout>
  );
};`,
        language: "typescript",
      },
      {
        title: "重点总结",
        description: "设计稿转代码的核心要点",
        prompt: `# 📋 最佳实践
• 提供清晰的设计稿截图
• 明确技术栈（React + Ant Design）
• 采用迭代优化策略
• 保存成功的提示词模板

# ⚠️ 注意事项
• 复杂布局分模块处理
• 动画效果单独描述
• 自定义组件需提供示例

# 🚀 进阶技巧

## 1. 建立设计稿组件库映射表
• Button (Primary) → <Button type="primary">
• Card (Shadow) → <Card className="shadow-lg">
• Input (Large) → <Input size="large">
• Grid (12 columns) → <Row gutter={16}>

## 2. 积累常用提示词模板
• 保存成功的提示词到团队知识库
• 为不同类型页面创建模板
• 定期更新和优化模板

## 3. 团队统一使用规范
• 统一的命名规则
• 一致的文件结构
• 共享的样式变量
• 标准的组件拆分原则

## 4. 定期更新项目上下文
• 每周更新.claude/prompts.md
• 记录新增的设计规范
• 更新技术栈和依赖
• 添加常见问题解决方案`,
        code: `// utils/design-system-mapper.js
export const designSystemMap = {
  // 颜色映射
  colors: {
    'primary-blue': '#1890ff',
    'success-green': '#52c41a',
    'warning-orange': '#faad14',
    'error-red': '#f5222d'
  },

  // 间距映射
  spacing: {
    xs: '8px', sm: '12px',
    md: '16px', lg: '24px', xl: '32px'
  },

  // 组件映射
  components: {
    'primary-button': {
      component: 'Button',
      props: { type: 'primary' }
    },
    'card-container': {
      component: 'Card',
      props: { hoverable: true }
    }
  }
};

// 提示词模板管理
export const promptTemplates = {
  landingPage: '生成落地页...',
  dashboard: '生成数据看板...',
  form: '生成表单页面...',
  table: '生成表格页面...'
};`,
        language: "javascript",
      },
    ],
  },
  {
    id: "form-table",
    title: "表单表格快速生成",
    type: "code",
    description: "通过描述字段和业务需求，快速生成CRUD页面",
    examples: [
      {
        title: "表格组件提示词",
        description: "完整的表格功能需求描述",
        prompt: `创建一个员工管理表格组件，包含以下功能：

## 字段信息
- 员工姓名 (name: string) - 必填
- 工号 (employeeId: string) - 唯一
- 部门 (department: string) - 下拉选择
- 职位 (position: string)
- 入职日期 (joinDate: Date)
- 状态 (status: 'active' | 'inactive') - 标签显示

## 功能需求
1. 支持分页（每页10条）
2. 支持按姓名、工号搜索
3. 支持按部门、状态筛选
4. 支持按入职日期排序
5. 批量操作（删除、导出）
6. 行内编辑状态
7. 操作列：编辑、删除、查看详情

## 技术要求
- 使用Ant Design的Table组件
- TypeScript严格类型定义
- 使用Hooks管理状态
- 实现Loading和Empty状态`,
        code: `import { Table, Button, Space, Input, Select, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';

interface Employee {
  id: string;
  name: string;
  employeeId: string;
  department: string;
  position: string;
  joinDate: string;
  status: 'active' | 'inactive';
}

const columns: ColumnsType<Employee> = [
  {
    title: '员工姓名',
    dataIndex: 'name',
    key: 'name',
    fixed: 'left',
    render: (text, record) => (
      <a onClick={() => handleView(record)}>{text}</a>
    )
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '在职', value: 'active' },
      { text: '离职', value: 'inactive' }
    ],
    render: (status) => (
      <Tag color={status === 'active' ? 'green' : 'red'}>
        {status === 'active' ? '在职' : '离职'}
      </Tag>
    )
  }
];`,
        language: "typescript",
      },
      {
        title: "表单组件提示词",
        description: "复杂表单的完整描述",
        prompt: `创建一个员工信息表单，要求：

## 表单字段
### 基础信息
- 姓名：必填，2-20个字符
- 工号：必填，自动生成，格式EMP-YYYYMMDD-XXX
- 性别：单选
- 出生日期：日期选择器，不能超过今天
- 手机号：11位，正则验证

### 工作信息
- 部门：级联选择器（公司-部门-小组）
- 职位：下拉选择
- 入职日期：必填
- 工作邮箱：自动生成@company.com

## 表单特性
1. 分步骤填写（3步）
2. 实时保存草稿
3. 字段联动（选择部门后更新职位选项）
4. 自定义验证规则
5. 提交前预览`,
        code: `import { Form, Input, Select, DatePicker, Steps } from 'antd';

const [form] = Form.useForm();
const [currentStep, setCurrentStep] = useState(0);

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名' },
    { min: 2, max: 20, message: '姓名长度2-20个字符' }
  ],
  phone: [
    { required: true, message: '请输入手机号' },
    { pattern: /^1[3-9]\d{9}\$/, message: '请输入正确的手机号' }
  ]
};

// 字段联动
const handleDepartmentChange = (value) => {
  // 根据部门更新职位选项
  const positions = getPositionsByDepartment(value);
  form.setFieldsValue({ position: undefined });
  setPositionOptions(positions);
};

// 自动生成工号
const generateEmployeeId = () => {
  const date = dayjs().format('YYYYMMDD');
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return \`EMP-\${date}-\${random}\`;
};`,
        language: "typescript",
      },
      {
        title: "高级技巧",
        description: "提高生成代码质量的技巧",
        prompt: `# 表单表格生成高级技巧

## 1. 提供数据结构
\`\`\`json
{
  "employee": {
    "id": "uuid",
    "name": "string",
    "department": {
      "id": "string",
      "name": "string"
    },
    "permissions": ["string"]
  }
}
\`\`\`

## 2. 指定业务规则
- 工号不可修改
- 部门变更需要审批
- 删除操作需要二次确认
- 敏感信息脱敏显示

## 3. 性能优化要求
- 虚拟滚动（数据量>1000）
- 防抖搜索（300ms）
- 懒加载子表数据
- 缓存筛选结果

## 4. 用户体验
- 保存草稿提示
- 离开页面确认
- 批量操作进度条
- 操作成功/失败反馈`,
        code: `// 虚拟滚动表格
import VirtualTable from '@/components/VirtualTable';

// 防抖搜索
const debouncedSearch = useMemo(
  () => debounce(handleSearch, 300),
  []
);

// 草稿保存
useEffect(() => {
  const timer = setInterval(() => {
    if (form.isFieldsTouched()) {
      saveDraft(form.getFieldsValue());
    }
  }, 30000); // 30秒自动保存

  return () => clearInterval(timer);
}, []);

// 离开页面提示
useBeforeUnload(
  hasUnsavedChanges,
  '您有未保存的更改，确定要离开吗？'
);`,
        language: "typescript",
      },
      {
        title: "重点总结",
        description: "表单表格生成的核心要点",
        prompt: `# 📋 最佳实践
• 详细描述字段类型和验证规则
• 说明业务逻辑和联动关系
• 指定UI组件和交互方式
• 提供数据结构示例

# ⚠️ 注意事项
• 复杂表单分步骤设计
• 大数据使用虚拟滚动
• 敏感操作二次确认
• 批量操作进度反馈

# 🚀 进阶技巧
• Schema驱动开发
• JSON配置生成
• 低代码平台集成`,
        code: `// Schema驱动示例
const formSchema = {
  fields: [
    { name: 'username', type: 'string', rules: ['required', 'min:2'] },
    { name: 'department', type: 'select', options: departments }
  ],
  layout: 'horizontal',
  actions: ['submit', 'reset', 'save-draft']
};

// 自动生成完整表单
const DynamicForm = generateForm(formSchema);`,
        language: "typescript",
      },
    ],
  },
  {
    id: "api-integration",
    title: "接口联调技巧",
    type: "code",
    description: "快速生成API请求封装和Mock数据",
    examples: [
      {
        title: "API请求封装",
        description: "Claude生成的统一请求处理",
        code: `import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { message } from 'antd';

class Request {
  private instance: AxiosInstance;

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.setupInterceptors();
  }

  private setupInterceptors() {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token');
        if (token) {
          config.headers.Authorization = \`Bearer \${token}\`;
        }
        return config;
      },
      (error) => Promise.reject(error)
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => response.data,
      (error) => {
        const { response } = error;
        if (response?.status === 401) {
          // 跳转登录
          window.location.href = '/login';
        } else {
          message.error(response?.data?.message || '请求失败');
        }
        return Promise.reject(error);
      }
    );
  }

  get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.post(url, data, config);
  }

  put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.put(url, data, config);
  }

  delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
}

export default new Request({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 10000,
});`,
        language: "typescript",
      },
      {
        title: "Mock数据生成",
        description: "自动生成测试数据",
        code: `// Claude可以根据接口描述生成Mock数据
export const mockUsers = Array.from({ length: 100 }, (_, i) => ({
  id: \`user-\${i + 1}\`,
  name: \`用户\${i + 1}\`,
  email: \`user\${i + 1}@example.com\`,
  department: ['技术部', '产品部', '市场部'][i % 3],
  position: ['工程师', '经理', '总监'][i % 3],
  status: i % 5 === 0 ? 'inactive' : 'active',
  joinDate: new Date(2020, 0, 1 + i).toISOString(),
  avatar: \`https://api.dicebear.com/7.x/avataaars/svg?seed=\${i}\`
}));`,
        language: "typescript",
      },
      {
        title: "接口返回数据处理",
        description: "根据真实接口返回数据，生成精确的TypeScript类型和数据处理逻辑",
        prompt: `这是后端接口返回的数据结构：
{
  "code": 200,
  "message": "success",
  "data": {
    "list": [
      {
        "id": 1,
        "orderNo": "ORD20240101001",
        "customerInfo": {
          "name": "张三",
          "phone": "13800138000",
          "address": {
            "province": "广东省",
            "city": "深圳市",
            "detail": "南山区科技园"
          }
        },
        "products": [
          {
            "productId": "P001",
            "productName": "商品A",
            "quantity": 2,
            "price": 99.9,
            "specifications": ["红色", "XL"]
          }
        ],
        "totalAmount": 199.8,
        "status": 1,
        "createTime": "2024-01-01T10:00:00Z"
      }
    ],
    "total": 100,
    "pageNum": 1,
    "pageSize": 10
  }
}

请帮我：
1. 生成TypeScript类型定义
2. 创建数据处理hooks
3. 生成表格展示组件`,
        code: `// 1. TypeScript类型定义
interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

interface Address {
  province: string;
  city: string;
  detail: string;
}

interface CustomerInfo {
  name: string;
  phone: string;
  address: Address;
}

interface Product {
  productId: string;
  productName: string;
  quantity: number;
  price: number;
  specifications: string[];
}

interface Order {
  id: number;
  orderNo: string;
  customerInfo: CustomerInfo;
  products: Product[];
  totalAmount: number;
  status: number;
  createTime: string;
}

interface OrderListData {
  list: Order[];
  total: number;
  pageNum: number;
  pageSize: number;
}

// 2. 数据处理hooks
import { useState, useEffect, useCallback } from 'react';
import { message } from 'antd';
import request from '@/utils/request';

export const useOrderList = () => {
  const [loading, setLoading] = useState(false);
  const [orders, setOrders] = useState<Order[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  const fetchOrders = useCallback(async (params?: {
    pageNum?: number;
    pageSize?: number;
  }) => {
    setLoading(true);
    try {
      const res = await request.get<ApiResponse<OrderListData>>('/api/orders', {
        params: {
          pageNum: params?.pageNum || pagination.current,
          pageSize: params?.pageSize || pagination.pageSize
        }
      });

      if (res.code === 200) {
        setOrders(res.data.list);
        setPagination({
          current: res.data.pageNum,
          pageSize: res.data.pageSize,
          total: res.data.total
        });
      } else {
        message.error(res.message || '获取订单列表失败');
      }
    } catch (error) {
      message.error('请求失败，请重试');
    } finally {
      setLoading(false);
    }
  }, [pagination]);

  // 数据格式化函数
  const formatOrderStatus = (status: number) => {
    const statusMap: Record<number, { text: string; color: string }> = {
      0: { text: '待付款', color: 'warning' },
      1: { text: '待发货', color: 'processing' },
      2: { text: '已发货', color: 'cyan' },
      3: { text: '已完成', color: 'success' },
      4: { text: '已取消', color: 'default' }
    };
    return statusMap[status] || { text: '未知', color: 'default' };
  };

  const formatDateTime = (dateStr: string) => {
    return new Date(dateStr).toLocaleString('zh-CN');
  };

  return {
    loading,
    orders,
    pagination,
    fetchOrders,
    formatOrderStatus,
    formatDateTime
  };
};

// 3. 表格展示组件
import React from 'react';
import { Table, Tag, Space, Tooltip } from 'antd';
import type { ColumnsType } from 'antd/es/table';

const OrderTable: React.FC = () => {
  const {
    loading,
    orders,
    pagination,
    fetchOrders,
    formatOrderStatus,
    formatDateTime
  } = useOrderList();

  const columns: ColumnsType<Order> = [
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      key: 'orderNo',
      width: 150,
      fixed: 'left'
    },
    {
      title: '客户信息',
      key: 'customerInfo',
      render: (_, record) => (
        <Space direction="vertical" size="small">
          <span>{record.customerInfo.name}</span>
          <span className="text-gray-500">{record.customerInfo.phone}</span>
          <Tooltip title={
            \`\${record.customerInfo.address.province}\${record.customerInfo.address.city}\${record.customerInfo.address.detail}\`
          }>
            <span className="text-gray-400 cursor-pointer">查看地址</span>
          </Tooltip>
        </Space>
      )
    },
    {
      title: '商品信息',
      key: 'products',
      render: (_, record) => (
        <Space direction="vertical" size="small">
          {record.products.slice(0, 2).map((product, index) => (
            <div key={index}>
              <span>{product.productName}</span>
              <span className="text-gray-500 ml-2">x{product.quantity}</span>
            </div>
          ))}
          {record.products.length > 2 && (
            <span className="text-blue-500">+{record.products.length - 2}件商品</span>
          )}
        </Space>
      )
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => <span className="font-semibold">¥{amount.toFixed(2)}</span>
    },
    {
      title: '订单状态',
      key: 'status',
      render: (_, record) => {
        const status = formatOrderStatus(record.status);
        return <Tag color={status.color}>{status.text}</Tag>;
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => formatDateTime(time)
    }
  ];

  useEffect(() => {
    fetchOrders();
  }, []);

  const handleTableChange = (pagination: any) => {
    fetchOrders({
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    });
  };

  return (
    <Table
      columns={columns}
      dataSource={orders}
      rowKey="id"
      loading={loading}
      pagination={pagination}
      onChange={handleTableChange}
      scroll={{ x: 1200 }}
    />
  );
};

export default OrderTable;`,
        language: "typescript",
      },
    ],
  },
  {
    id: "permission",
    title: "权限控制实现",
    type: "code",
    description: "多层级权限控制方案",
    examples: [
      {
        title: "路由权限控制",
        code: `import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import { useAuthStore } from '@/stores/auth';

interface ProtectedRouteProps {
  permissions?: string[];
  roles?: string[];
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  permissions = [],
  roles = []
}) => {
  const { user, hasPermission, hasRole } = useAuthStore();

  if (!user) {
    return <Navigate to="/login" replace />;
  }

  const hasRequiredPermission = permissions.length === 0 ||
    permissions.some(p => hasPermission(p));

  const hasRequiredRole = roles.length === 0 ||
    roles.some(r => hasRole(r));

  if (!hasRequiredPermission || !hasRequiredRole) {
    return <Navigate to="/403" replace />;
  }

  return <Outlet />;
};

// 使用示例
const routes = [
  {
    path: '/admin',
    element: <ProtectedRoute roles={['admin']} />,
    children: [
      { path: 'users', element: <UserManagement /> },
      { path: 'settings', element: <Settings /> }
    ]
  }
];`,
        language: "typescript",
      },
      {
        title: "按钮级权限",
        code: `import React from 'react';
import { Button, ButtonProps } from 'antd';
import { useAuthStore } from '@/stores/auth';

interface PermissionButtonProps extends ButtonProps {
  permission?: string;
  fallback?: React.ReactNode;
}

const PermissionButton: React.FC<PermissionButtonProps> = ({
  permission,
  fallback = null,
  children,
  ...props
}) => {
  const { hasPermission } = useAuthStore();

  if (permission && !hasPermission(permission)) {
    return <>{fallback}</>;
  }

  return <Button {...props}>{children}</Button>;
};

// 使用示例
<PermissionButton
  permission="user:delete"
  type="danger"
  onClick={handleDelete}
>
  删除用户
</PermissionButton>`,
        language: "typescript",
      },
      {
        title: "菜单权限控制",
        description: "根据用户权限动态生成菜单",
        code: `import React, { useMemo } from 'react';
import { Menu, Layout } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import {
  DashboardOutlined,
  UserOutlined,
  SettingOutlined,
  FileTextOutlined,
  TeamOutlined,
  BarChartOutlined,
  SafetyOutlined,
  ShoppingCartOutlined
} from '@ant-design/icons';
import { useAuthStore } from '@/stores/auth';

const { Sider } = Layout;

// 完整的菜单配置
interface MenuItem {
  key: string;
  label: string;
  icon?: React.ReactNode;
  path?: string;
  permission?: string;  // 需要的权限
  roles?: string[];     // 需要的角色
  children?: MenuItem[];
}

const allMenuItems: MenuItem[] = [
  {
    key: 'dashboard',
    label: '仪表盘',
    icon: <DashboardOutlined />,
    path: '/dashboard',
    permission: 'dashboard:view'
  },
  {
    key: 'user',
    label: '用户管理',
    icon: <UserOutlined />,
    permission: 'user:manage',
    children: [
      {
        key: 'user-list',
        label: '用户列表',
        path: '/users/list',
        permission: 'user:list'
      },
      {
        key: 'user-role',
        label: '角色管理',
        path: '/users/roles',
        permission: 'role:manage',
        roles: ['admin']
      },
      {
        key: 'user-permission',
        label: '权限配置',
        path: '/users/permissions',
        permission: 'permission:manage',
        roles: ['super-admin']
      }
    ]
  },
  {
    key: 'order',
    label: '订单管理',
    icon: <ShoppingCartOutlined />,
    permission: 'order:view',
    children: [
      {
        key: 'order-list',
        label: '订单列表',
        path: '/orders/list',
        permission: 'order:list'
      },
      {
        key: 'order-refund',
        label: '退款管理',
        path: '/orders/refund',
        permission: 'order:refund'
      }
    ]
  },
  {
    key: 'report',
    label: '报表中心',
    icon: <BarChartOutlined />,
    path: '/reports',
    permission: 'report:view',
    roles: ['admin', 'manager']
  },
  {
    key: 'system',
    label: '系统设置',
    icon: <SettingOutlined />,
    permission: 'system:manage',
    roles: ['admin'],
    children: [
      {
        key: 'system-config',
        label: '系统配置',
        path: '/system/config',
        permission: 'system:config'
      },
      {
        key: 'system-log',
        label: '操作日志',
        path: '/system/logs',
        permission: 'system:log'
      }
    ]
  }
];

// 菜单权限过滤Hook
const useMenuPermission = () => {
  const { user, permissions, roles } = useAuthStore();

  const filterMenuItems = (items: MenuItem[]): MenuItem[] => {
    return items
      .filter(item => {
        // 检查权限
        if (item.permission && !permissions.includes(item.permission)) {
          return false;
        }

        // 检查角色
        if (item.roles && item.roles.length > 0) {
          const hasRole = item.roles.some(role => roles.includes(role));
          if (!hasRole) return false;
        }

        // 递归过滤子菜单
        if (item.children) {
          const filteredChildren = filterMenuItems(item.children);
          // 如果没有可见的子菜单，隐藏父菜单
          if (filteredChildren.length === 0) {
            return false;
          }
          // 更新子菜单
          item.children = filteredChildren;
        }

        return true;
      });
  };

  const menuItems = useMemo(() => {
    if (!user) return [];
    return filterMenuItems(JSON.parse(JSON.stringify(allMenuItems)));
  }, [user, permissions, roles]);

  return menuItems;
};

// Ant Design Menu组件格式化
const formatAntdMenuItems = (items: MenuItem[]): any[] => {
  return items.map(item => {
    const menuItem: any = {
      key: item.key,
      icon: item.icon,
      label: item.path ? (
        <Link to={item.path}>{item.label}</Link>
      ) : (
        item.label
      )
    };

    if (item.children && item.children.length > 0) {
      menuItem.children = formatAntdMenuItems(item.children);
    }

    return menuItem;
  });
};

// 侧边栏菜单组件
const SidebarMenu: React.FC = () => {
  const location = useLocation();
  const menuItems = useMenuPermission();
  const antdMenuItems = formatAntdMenuItems(menuItems);

  // 获取当前选中的菜单项
  const selectedKeys = useMemo(() => {
    const findSelectedKey = (items: MenuItem[], path: string): string[] => {
      for (const item of items) {
        if (item.path === path) {
          return [item.key];
        }
        if (item.children) {
          const childKey = findSelectedKey(item.children, path);
          if (childKey.length > 0) {
            return childKey;
          }
        }
      }
      return [];
    };
    return findSelectedKey(menuItems, location.pathname);
  }, [location.pathname, menuItems]);

  // 获取默认展开的菜单项
  const defaultOpenKeys = useMemo(() => {
    const findParentKeys = (items: MenuItem[], path: string): string[] => {
      for (const item of items) {
        if (item.children) {
          const hasChild = item.children.some(child => child.path === path);
          if (hasChild) {
            return [item.key];
          }
          const childKeys = findParentKeys(item.children, path);
          if (childKeys.length > 0) {
            return [item.key, ...childKeys];
          }
        }
      }
      return [];
    };
    return findParentKeys(menuItems, location.pathname);
  }, [location.pathname, menuItems]);

  return (
    <Sider width={200} className="site-layout-background">
      <Menu
        mode="inline"
        selectedKeys={selectedKeys}
        defaultOpenKeys={defaultOpenKeys}
        style={{ height: '100%', borderRight: 0 }}
        items={antdMenuItems}
      />
    </Sider>
  );
};

// 权限Store示例
interface AuthState {
  user: User | null;
  permissions: string[];
  roles: string[];
}

// 模拟不同用户的权限数据
const mockUserPermissions = {
  admin: {
    roles: ['admin'],
    permissions: [
      'dashboard:view',
      'user:manage',
      'user:list',
      'role:manage',
      'order:view',
      'order:list',
      'order:refund',
      'report:view',
      'system:manage',
      'system:config',
      'system:log'
    ]
  },
  manager: {
    roles: ['manager'],
    permissions: [
      'dashboard:view',
      'user:list',
      'order:view',
      'order:list',
      'report:view'
    ]
  },
  operator: {
    roles: ['operator'],
    permissions: [
      'dashboard:view',
      'order:view',
      'order:list'
    ]
  }
};

export { SidebarMenu, useMenuPermission };`,
        language: "typescript",
      },
    ],
  },
  {
    id: "bug-fixing",
    title: "Bug修复",
    subtitle: "快速定位问题",
    type: "code",
    description:
      "Claude可以帮助快速定位和修复各种Bug，提供详细的问题分析和解决方案",
    tags: ["调试", "问题定位", "性能优化"],
    examples: [
      {
        title: "错误分析示例",
        description: "让Claude分析错误信息并提供解决方案",
        language: "markdown",
        prompt: `我遇到了一个React渲染错误：
Error: Maximum update depth exceeded.
This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.

组件代码：
\`\`\`jsx
function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1);
  });

  return <div>{count}</div>;
}
\`\`\`

请帮我分析问题原因并提供修复方案`,
        code: `// 问题分析：
// useEffect没有依赖数组，导致每次渲染都会执行，形成无限循环

// 修复方案1：添加空依赖数组（只执行一次）
function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    setCount(count + 1);
  }, []); // 只在组件挂载时执行一次

  return <div>{count}</div>;
}

// 修复方案2：添加条件控制
function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    if (count < 10) {
      setCount(count + 1);
    }
  }, [count]); // 依赖count，但有条件限制

  return <div>{count}</div>;
}`,
      },
      {
        title: "性能优化",
        description: "让Claude分析性能问题并优化",
        language: "jsx",
        code: `// 优化前：大列表渲染性能问题
function ProductList({ products }) {
  return (
    <div>
      {products.map(product => (
        <div key={product.id}>
          <h3>{product.name}</h3>
          <p>{product.price}</p>
          <button onClick={() => addToCart(product)}>
            加入购物车
          </button>
        </div>
      ))}
    </div>
  );
}

// 优化后：使用React.memo和useCallback
const ProductItem = React.memo(({ product, onAddToCart }) => {
  return (
    <div>
      <h3>{product.name}</h3>
      <p>{product.price}</p>
      <button onClick={() => onAddToCart(product)}>
        加入购物车
      </button>
    </div>
  );
});

function ProductList({ products }) {
  const handleAddToCart = useCallback((product) => {
    addToCart(product);
  }, []);

  return (
    <div>
      {products.map(product => (
        <ProductItem
          key={product.id}
          product={product}
          onAddToCart={handleAddToCart}
        />
      ))}
    </div>
  );
}`,
      },
      {
        title: "调试技巧总结",
        description: "有效的调试提示词模板",
        language: "markdown",
        code: `## Bug修复最佳实践

### 1. 提供完整的错误信息
- 错误消息全文
- 错误堆栈信息
- 相关代码片段
- 复现步骤

### 2. 有效的提示词模板
\`\`\`
我遇到了 [错误类型] 问题：
错误信息：[完整错误信息]
复现步骤：[如何复现]
相关代码：[代码片段]
期望行为：[应该如何工作]
\`\`\`

### 3. 常见问题类型
- 渲染错误：组件生命周期问题
- 状态更新：异步更新、批处理
- 性能问题：重渲染、大数据处理
- 内存泄漏：事件监听器、定时器清理

### 4. Claude调试优势
✅ 快速定位问题根源
✅ 提供多种解决方案
✅ 解释问题原因
✅ 预防类似问题`,
      },
    ],
  },
  {
    id: "complex-module",
    title: "复杂模块实现",
    type: "code",
    description: "使用Plan Mode和思考模型，快速理解和实现复杂业务逻辑",
    examples: [
      {
        title: "Plan Mode使用",
        description: "让Claude先规划实现步骤，再逐步执行",
        prompt: `我需要实现一个复杂的数据可视化面板：

要求：
1. 支持多种图表类型（折线图、柱状图、饼图、热力图）
2. 实时数据更新（WebSocket）
3. 图表联动和数据钻取
4. 自定义图表配置和布局
5. 数据导出功能

请先进入Plan Mode，制定详细的实现计划`,
        code: `// Claude的实现计划
## 实现步骤规划

### 第一阶段：基础架构搭建
1. 创建图表组件基类
2. 实现图表配置管理器
3. 搭建WebSocket连接层

### 第二阶段：图表组件开发
1. 封装ECharts基础组件
2. 实现各类图表组件
3. 添加响应式布局

### 第三阶段：交互功能
1. 实现图表联动机制
2. 添加数据钻取功能
3. 自定义配置面板

### 第四阶段：优化与增强
1. 性能优化（虚拟滚动、缓存）
2. 错误处理和降级
3. 数据导出功能

// 具体实现代码...`,
        language: "typescript",
      },
      {
        title: "思考模型应用",
        description: "让Claude深度分析业务逻辑，找出最优解决方案",
        prompt: `分析这个复杂的权限系统需求：

1. 多租户架构，每个租户独立的权限体系
2. 支持RBAC和ABAC混合模式
3. 动态权限，可根据时间、地点、设备等条件控制
4. 权限继承和覆盖机制
5. 审计日志和权限变更追踪

请使用思考模型，分析各种实现方案的优缺点`,
        code: `// Claude的思考分析结果
interface PermissionSystem {
  // 多租户隔离
  tenantId: string;

  // RBAC部分
  roles: Map<string, Role>;
  userRoles: Map<string, Set<string>>;

  // ABAC部分
  policies: Policy[];
  attributes: AttributeStore;

  // 动态权限评估
  evaluate(context: PermissionContext): boolean {
    // 1. 检查租户隔离
    if (context.tenantId !== this.tenantId) return false;

    // 2. RBAC检查
    const hasRole = this.checkRBAC(context.userId);

    // 3. ABAC策略评估
    const policyResult = this.evaluatePolicies(context);

    // 4. 动态条件检查
    const dynamicCheck = this.checkDynamicConditions(context);

    // 5. 审计日志
    this.auditLog(context, hasRole && policyResult && dynamicCheck);

    return hasRole && policyResult && dynamicCheck;
  }
}

// 实现优势分析：
// 1. 灵活性：支持多种权限模型
// 2. 性能：使用缓存和索引优化
// 3. 可维护性：清晰的分层结构
// 4. 可扩展性：易于添加新的权限类型`,
        language: "typescript",
      },
      {
        title: "代码快速上手",
        description: "让Claude分析现有代码库，快速理解项目结构",
        prompt: `这是一个大型项目的目录结构，请帮我快速理解：

src/
├── modules/
│   ├── auth/
│   ├── dashboard/
│   └── reporting/
├── shared/
│   ├── components/
│   ├── hooks/
│   └── utils/
├── core/
│   ├── services/
│   ├── store/
│   └── router/

请分析项目架构，并指出关键模块的作用`,
        code: `// Claude的项目分析
## 项目架构分析

### 整体架构模式
- 采用模块化架构(Modular Architecture)
- 基于领域驱动设计(DDD)原则
- 清晰的分层结构

### 核心模块解析

1. **modules/** - 业务模块
   - auth: 认证授权模块
   - dashboard: 数据看板
   - reporting: 报表系统

2. **shared/** - 共享资源
   - components: 通用UI组件
   - hooks: 自定义React Hooks
   - utils: 工具函数库

3. **core/** - 核心基础设施
   - services: API服务层
   - store: 状态管理(Redux/Zustand)
   - router: 路由配置

### 快速上手建议
1. 先看 core/router 了解页面结构
2. 查看 core/services 了解API调用
3. 从 modules/dashboard 开始了解业务逻辑
4. shared/components 查看UI组件库

### 关键文件定位
- 入口文件: src/main.tsx
- 路由配置: core/router/index.ts
- 全局状态: core/store/index.ts
- API配置: core/services/api.config.ts`,
        language: "typescript",
      },
    ],
  },
  {
    id: "git-workflow",
    title: "工作流程管理",
    type: "code",
    description: "使用Claude自动化Git操作和版本管理",
    examples: [
      {
        title: "智能提交信息生成",
        description: "Claude根据代码变更自动生成规范的commit message",
        prompt: `请根据以下git diff生成commit message：
- 添加了用户认证功能
- 修复了登录表单验证bug
- 更新了API接口文档`,
        code: `# Claude生成的提交信息
feat(auth): implement user authentication system

- Add JWT-based authentication
- Create login/logout endpoints
- Implement token refresh mechanism
- Add user session management

fix(form): resolve login form validation issues
- Fix email regex pattern
- Add password strength validation
- Handle form submission errors

docs(api): update API documentation
- Add authentication endpoints
- Update request/response examples
- Include error codes reference

Closes #156, #158`,
        language: "bash",
      },
      {
        title: "分支管理策略",
        description: "自动创建和管理feature分支",
        code: `#!/bin/bash
# Claude生成的分支管理脚本

# 创建feature分支
create_feature_branch() {
  local feature_name=\$1
  local base_branch=\${2:-develop}

  echo "Creating feature branch: feature/\$feature_name"
  git checkout \$base_branch
  git pull origin \$base_branch
  git checkout -b feature/\$feature_name
  git push -u origin feature/\$feature_name
}

# 合并feature到develop
merge_feature() {
  local feature_name=\$1

  echo "Merging feature/\$feature_name to develop"
  git checkout develop
  git pull origin develop
  git merge --no-ff feature/\$feature_name -m "Merge feature/\$feature_name into develop"
  git push origin develop

  # 清理本地和远程分支
  git branch -d feature/\$feature_name
  git push origin --delete feature/\$feature_name
}

# 冲突解决助手
resolve_conflicts() {
  echo "Detecting conflicts..."
  git status --short | grep "^UU" | awk '{print $2}' | while read file; do
    echo "Conflict in: \$file"
    echo "Opening in editor..."
    code \$file
  done
}`,
        language: "bash",
      },
      {
        title: "GitLab CI/CD配置",
        description: "一键生成完整的CI/CD流水线配置",
        prompt: "为React项目配置GitLab CI，包含测试、构建、部署阶段",
        code: `stages:
  - install
  - test
  - build
  - deploy

variables:
  PNPM_CACHE_FOLDER: ".pnpm-store"

cache:
  key: \${CI_COMMIT_REF_SLUG}
  paths:
    - .pnpm-store/
    - node_modules/

install:dependencies:
  stage: install
  image: node:18-alpine
  before_script:
    - npm install -g pnpm@8
  script:
    - pnpm install --frozen-lockfile
  artifacts:
    paths:
      - node_modules/
    expire_in: 1 day

test:unit:
  stage: test
  needs: ["install:dependencies"]
  script:
    - pnpm test:unit --coverage
  coverage: '/All files[^|]*\\|[^|]*\\s+([\\d\\.]+)/'
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage/cobertura-coverage.xml

build:production:
  stage: build
  needs: ["test:unit"]
  script:
    - pnpm build
  artifacts:
    paths:
      - dist/
    expire_in: 7 days
  only:
    - main

deploy:production:
  stage: deploy
  needs: ["build:production"]
  script:
    - rsync -avz dist/ \$DEPLOY_USER@\$DEPLOY_HOST:/var/www/app/
  environment:
    name: production
    url: https://example.com
  only:
    - main`,
        language: "yaml",
      },
    ],
  },
  {
    id: "legacy-ci",
    title: "方案快速验证",
    type: "code",
    description: "快速验证技术方案的可行性，以CI/CD实现为例",
    examples: [
      {
        title: "Node.js Webhook服务",
        description: "接收GitLab webhook，触发构建流程",
        code: `import express from 'express';
import { exec } from 'child_process';
import crypto from 'crypto';
import Docker from 'dockerode';

const app = express();
const docker = new Docker();

// GitLab Webhook密钥验证
const verifyWebhookSignature = (req: Request) => {
  const token = req.headers['x-gitlab-token'];
  return token === process.env.GITLAB_WEBHOOK_TOKEN;
};

// 构建任务队列
class BuildQueue {
  private queue: Array<BuildTask> = [];
  private running = false;

  async add(task: BuildTask) {
    this.queue.push(task);
    if (!this.running) {
      this.process();
    }
  }

  private async process() {
    this.running = true;
    while (this.queue.length > 0) {
      const task = this.queue.shift()!;
      await this.executeBuild(task);
    }
    this.running = false;
  }

  private async executeBuild(task: BuildTask) {
    const { project, branch, commitId } = task;
    console.log(\`Building \${project}:\${branch}@\${commitId}\`);

    try {
      // 1. 拉取最新代码
      await execAsync(\`git clone -b \${branch} \${task.repoUrl} /tmp/\${commitId}\`);

      // 2. 安装依赖并构建
      await execAsync(\`cd /tmp/\${commitId} && npm ci && npm run build\`);

      // 3. 构建Docker镜像
      const imageName = \`\${project}:\${commitId}\`;
      await docker.buildImage({
        context: \`/tmp/\${commitId}\`,
        src: ['Dockerfile', 'dist']
      }, { t: imageName });

      // 4. 推送到仓库
      const image = docker.getImage(imageName);
      await image.push({
        registry: process.env.DOCKER_REGISTRY
      });

      // 5. 部署到服务器
      await this.deploy(imageName, project);

      // 6. 发送通知
      await this.notify('success', task);

    } catch (error) {
      console.error('Build failed:', error);
      await this.notify('failure', task);
    }
  }

  private async deploy(imageName: string, project: string) {
    // 通过SSH部署到目标服务器
    const deployScript = \`
      docker pull \${imageName}
      docker stop \${project} || true
      docker rm \${project} || true
      docker run -d --name \${project} -p 80:80 \${imageName}
    \`;

    await execAsync(\`ssh deploy@server '\${deployScript}'\`);
  }
}

// Webhook接收端点
app.post('/webhook/gitlab', express.json(), async (req, res) => {
  if (!verifyWebhookSignature(req)) {
    return res.status(401).send('Unauthorized');
  }

  const { project, ref, checkout_sha } = req.body;
  const branch = ref.replace('refs/heads/', '');

  // 添加到构建队列
  await buildQueue.add({
    project: project.name,
    branch,
    commitId: checkout_sha,
    repoUrl: project.git_http_url
  });

  res.json({ status: 'queued' });
});

app.listen(3001, () => {
  console.log('CI Server running on port 3001');
});`,
        language: "typescript",
      },
      {
        title: "Docker自动化部署",
        description: "构建镜像并部署到生产环境",
        code: `# Dockerfile - Claude生成的多阶段构建
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:18-alpine AS dev-deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

FROM dev-deps AS build
COPY . .
RUN npm run build

FROM nginx:alpine AS production
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]`,
        language: "dockerfile",
      },
    ],
  },
  {
    id: "i18n",
    title: "国际化配置",
    type: "code",
    description: "快速实现多语言支持",
    examples: [
      {
        title: "i18n配置",
        code: `import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

const resources = {
  zh: {
    translation: {
      welcome: '欢迎',
      user: {
        name: '姓名',
        email: '邮箱',
        department: '部门'
      },
      action: {
        add: '添加',
        edit: '编辑',
        delete: '删除',
        confirm: '确认',
        cancel: '取消'
      }
    }
  },
  en: {
    translation: {
      welcome: 'Welcome',
      user: {
        name: 'Name',
        email: 'Email',
        department: 'Department'
      },
      action: {
        add: 'Add',
        edit: 'Edit',
        delete: 'Delete',
        confirm: 'Confirm',
        cancel: 'Cancel'
      }
    }
  }
};

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources,
    fallbackLng: 'zh',
    interpolation: {
      escapeValue: false
    }
  });

export default i18n;`,
        language: "typescript",
      },
      {
        title: "组件中使用",
        code: `import React from 'react';
import { useTranslation } from 'react-i18next';
import { Select, Space } from 'antd';

const LanguageSwitcher: React.FC = () => {
  const { t, i18n } = useTranslation();

  return (
    <Space>
      <span>{t('welcome')}</span>
      <Select
        value={i18n.language}
        onChange={(value) => i18n.changeLanguage(value)}
        options={[
          { label: '中文', value: 'zh' },
          { label: 'English', value: 'en' }
        ]}
      />
    </Space>
  );
};`,
        language: "typescript",
      },
    ],
  },
  {
    id: "project-prompts",
    title: "项目级提示词配置",
    type: "code",
    description: "通过配置文件统一项目代码规范",
    examples: [
      {
        title: ".claude/prompts.md 配置文件",
        description: "在项目根目录创建配置文件，Claude会自动遵循",
        code: `# 项目规范

## 技术栈
- React 18 + TypeScript
- Ant Design 5
- Tailwind CSS
- GitLab CI/CD

## 代码规范
- 函数组件 + Hooks
- 使用React.FC定义组件
- Props解构在参数中进行
- 使用useMemo/useCallback优化

## 命名规范
- 组件：PascalCase
- 函数：camelCase
- 常量：UPPER_SNAKE_CASE
- CSS：kebab-case

## 文件结构
components/
  ComponentName/
    index.tsx       # 主文件
    styles.module.scss
    types.ts
    hooks.ts

## API规范
- RESTful风格
- 统一错误处理
- TypeScript类型定义`,
        language: "markdown",
      },
      {
        title: "使用效果",
        description: "Claude自动遵循项目规范生成代码",
        code: `// Claude会根据项目规范生成代码
import React, { useMemo, useCallback } from 'react';
import { Card, Button } from 'antd';
import styles from './styles.module.scss';
import { IUserCardProps } from './types';
import { useUserData } from './hooks';

const UserCard: React.FC<IUserCardProps> = ({ userId, onUpdate }) => {
  const { user, loading } = useUserData(userId);

  const fullName = useMemo(() => {
    return \`\${user?.firstName} \${user?.lastName}\`;
  }, [user]);

  const handleUpdate = useCallback(() => {
    onUpdate(userId);
  }, [userId, onUpdate]);

  return (
    <Card className={styles['user-card']} loading={loading}>
      <h2 className={styles['user-card-title']}>{fullName}</h2>
      <Button onClick={handleUpdate}>更新</Button>
    </Card>
  );
};

export default UserCard;`,
        language: "typescript",
      },
    ],
  },
  {
    id: "tips",
    title: "最佳实践技巧",
    type: "tips",
    tips: [
      {
        title: "明确需求描述",
        content: "提供具体的字段名称、类型、验证规则，Claude生成的代码会更精准",
        example:
          "姓名(name: string, 必填, 2-20字符), 邮箱(email: string, 必填, 邮箱格式)",
      },
      {
        title: "分步迭代",
        content: "先生成基础版本，再逐步添加功能，避免一次性需求过于复杂",
        example:
          "第一步：生成基础表格 → 第二步：添加搜索 → 第三步：添加编辑功能",
      },
      {
        title: "提供上下文",
        content: "告诉Claude你的技术栈和项目规范，生成的代码会更符合项目要求",
        example: "使用React 18, TypeScript, Ant Design 5, 遵循ESLint规则",
      },
      {
        title: "保存常用模板",
        content: "将常用的提示词保存为模板，方便复用",
        example: "创建CRUD页面模板、API接口模板、组件模板等",
      },
      {
        title: "代码审查",
        content: "Claude生成的代码要进行审查，确保符合安全和性能要求",
        example: "检查是否有XSS风险、是否有性能问题、是否符合团队规范",
      },
      {
        title: "持续学习",
        content: "Claude会不断更新，定期了解新功能和最佳实践",
        example: "关注官方更新、加入社区交流、分享使用经验",
      },
    ],
  },
  {
    id: "summary",
    title: "总结",
    type: "overview",
    items: [
      {
        icon: <RocketOutlined style={{ fontSize: '2rem', color: '#8B5CF6' }} />,
        title: "快速开发",
        description: "从设计稿到代码、从需求到实现，大幅缩短开发周期"
      },
      {
        icon: <SafetyOutlined style={{ fontSize: '2rem', color: '#EC4899' }} />,
        title: "代码质量",
        description: "遵循最佳实践，自动生成类型安全、规范统一的代码"
      },
      {
        icon: <BugOutlined style={{ fontSize: '2rem', color: '#06B6D4' }} />,
        title: "问题解决",
        description: "快速定位Bug、分析问题根源、提供多种解决方案"
      },
      {
        icon: <ToolOutlined style={{ fontSize: '2rem', color: '#10B981' }} />,
        title: "工作流程管理",
        description: "Git管理、CI/CD配置、项目规范，全流程自动化"
      },
      {
        icon: <CodeOutlined style={{ fontSize: '2rem', color: '#F59E0B' }} />,
        title: "最佳实践",
        description: "项目级配置、团队协作模板、持续优化迭代"
      },
      {
        icon: <DashboardOutlined style={{ fontSize: '2rem', color: '#EF4444' }} />,
        title: "适用场景",
        description: "原型开发、CRUD页面、复杂业务、性能优化全覆盖"
      }
    ],
    description: "Claude不仅是代码生成工具，更是提升团队整体开发效率的AI伙伴",
    tags: ["立即开始", "持续学习", "团队协作", "效率提升"]
  },
]
